package com.lgx.right.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lgx.common.basic.dao.GeneralJdbcDao;
import com.lgx.common.exception.DataException;
import com.lgx.common.web.Pagination;
import com.lgx.common.web.md5.MD5Utils;
import com.lgx.right.dao.ICardDao;
import com.lgx.right.dao.IUserDao;
import com.lgx.right.dao.IUserExpandDao;
import com.lgx.right.entity.Card;
import com.lgx.right.entity.User;
import com.lgx.right.entity.UserExpand;
import com.lgx.right.service.IUserService;
import com.lgx.right.util.CardUtils;
import com.lgx.right.util.PasswordUtils;

/**
 * 用户Service
 * 
 * @author acer
 *
 */
@Service("userService")
public class UserService implements IUserService {

	@Autowired
	private IUserDao userDao;
	
	@Autowired
	private ICardDao cardDao;
	
	@Autowired
	private GeneralJdbcDao baseDao;
	
	@Autowired
	private IUserExpandDao userExpandDao;
	
	public IUserExpandDao getUserExpandDao() {
		return userExpandDao;
	}

	public void setUserExpandDao(IUserExpandDao userExpandDao) {
		this.userExpandDao = userExpandDao;
	}

	public GeneralJdbcDao getBaseDao() {
		return baseDao;
	}

	public void setBaseDao(GeneralJdbcDao baseDao) {
		this.baseDao = baseDao;
	}

	public ICardDao getCardDao() {
		return cardDao;
	}

	public void setCardDao(ICardDao cardDao) {
		this.cardDao = cardDao;
	}

	public IUserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

	@Transactional
	public User createUser(User user) throws DataException {
		MD5Utils md5 = new MD5Utils();      //密码加密
		String md5Passwd = md5.toMD5(user.getPassword());
		user.setPassword(md5Passwd);
		this.userDao.createUser(user);
		
		UserExpand expand = new UserExpand();
		expand.setUser(user);
		expand.setDegree("1");
		expand.setLevel("1");
		expand.setFunType("0");
		expand.setGiftRecord("0");
		expand.setHeadImage("");
		expand.setPoints("");
		expand.setPointRecordDate(new Date());
		this.userExpandDao.createUserExpand(expand);
		
		return user;
	}

	@Transactional
	public User updateUser(User user) throws DataException {
		return this.userDao.updateUser(user);
	}

	@Transactional
	public void deleteUser(User user) throws DataException {
		this.userDao.deleteUser(user);
	}

	@Transactional
	public void deleteUserById(long id) throws DataException {
		this.userDao.deleteUserById(id);
	}

	public User findUserById(long id) {
		return this.userDao.findUserById(id);
	}

	public List<User> findUserByCondition(String name, String param) {
		return this.userDao.findUserList(name,param) ;
	}

	public List<User> findUserList(String sql,Object[] params, int pageSize, int pageNum) {
		return this.userDao.findUserList(sql, params, pageSize, pageNum);
	}

	public Pagination findUserPagination(String sql,Object[] params, int pageSize, int pageNum) {
		return this.userDao.findUserPagination(sql, params, pageSize, pageNum);
	}
	
	public Pagination findUserPagination(Object[] params, Class<?> clazz, int pageSize, int pageNum) {
		return this.userDao.findUserPagination(params, clazz, pageSize, pageNum);
	}

	/**
	 * 登录
	 */
	public User loginUser(String username, String password) {
		if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
			return null;
		}
		return this.userDao.loginUser(username, password) ;
	}

	public boolean checkMobileExists(String mobile) {
		List<User> users = this.findUserByCondition("mobile", mobile);
		if(users.size() == 0)
		{
			return false;
		}
		return true;
	}

	/**
	 * 分页查询
	 */
	@Override
	public Pagination findUserList(String type,long orgId,int usertype,String name, String card, String mobile,
			String registerTimeStar, String registerTimeEnd ,String orgName,String isMaster,int pageSize,
			int pageNum) {
		return this.userDao.findUserList(type,orgId,usertype,name,card,mobile,registerTimeStar,registerTimeEnd,orgName,isMaster, pageSize, pageNum);
	}

	/**
	 * 创建用户
	 * 当前card对象传递过来的为空，所以card由系统授予
	 */
	@Override
	public User createUser(User user, String card) throws DataException {
		Card ca = null;
		if(StringUtils.isEmpty(card))
		{
			card = CardUtils.createCard(CardUtils.BEGIN_CARD, baseDao);    //由系统创建一个卡号
		}else {
			ca = this.cardDao.findCardById(card);                          //去数据库查询对应卡号的ca对象
		}
		
		//创建用户对应的卡号
		if(ca == null){
			Card c = new Card();
			c.setId(card);       //把系统创建的卡号添加到card表
			c.setStatus(Card.CARD_NEW);
			c.setScore(0);
			try {
				ca = this.cardDao.createCard(c);
			} catch (DataException e) {
				e.printStackTrace();
			}
		}
		
		user.setCard(ca);    //将新添加的card的id赋值给user对应的列,完成映射
		
		//对添加的用户的密码执行假面加密处理
		MD5Utils md5 = new MD5Utils(); 
		String md5Passwd = md5.toMD5(user.getPassword());
		user.setPassword(md5Passwd);          //把加密过的密码重新赋值给user
		try {
			return this.userDao.createUser(user);                  
		} catch (DataException e) {
			e.printStackTrace();
			return null;
		}
	}

	
	public User modifyPassword(long userId, String password)
			throws DataException {
		User user = this.findUserById(userId);
		MD5Utils md5 = new MD5Utils(); 
		String md5Passwd = md5.toMD5(password);
		user.setPassword(md5Passwd);
		this.updateUser(user);
		return user;
	}

	@Override
	public String modifyPassword(long userId, String npwd, String opwd)
			throws DataException {
		User user = this.findUserById(userId);  //根据id查找出这个用户
		MD5Utils md5 = new MD5Utils(); 
		String md5opwd = md5.toMD5(opwd);     //加密元秘密啊
		
		if(md5opwd.equals(user.getPassword()))  //判断，如果输入的原密码不等于数据库中保存的，表示这个用户还没有权限修改密码
		{
			String md5npwd = md5.toMD5(npwd);
			user.setPassword(md5npwd);
			try {
				this.userDao.updateUser(user);
			} catch (Exception e) {
				e.printStackTrace();
				return "2";
			}
		}else {
			//输入的旧密码不正确
			return "0";
		}
		return "1";
	}

	@Override
	public boolean resetPassword(long userId) throws DataException {
		User user = this.findUserById(userId);
		MD5Utils md5 = new MD5Utils(); 
		String md5Passwd = md5.toMD5(PasswordUtils.passwordRandom());
		user.setPassword(md5Passwd);
		try {
			this.updateUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		//当更新成功时，需要发送短信
		
		return true;
	}

	/**
	 * 检查用户名是否存在，一般使用情况，添加用户或者修改登录名
	 */
	@Override
	public boolean checkUserNameExists(String username) {
		List<User> users = this.findUserByCondition("username", username);
		if(users.size() == 0)
		{
			return false;
		}
		return true;
	}

	/**
	 * 更改用户绑定手机号码
	 */
	@Override
	public User updateUserMobile(Long userId, String mobile) throws DataException{
		//创建user对象
		User user = userDao.findUserById(userId);       //先根据userid查找到user对象的全部信息，在吧某个信息修改后提交
		user.setMobile(mobile);                         //把电话号码重新赋值给这个user，在把整个user对象update
		//把参数设置到user中
		return userDao.updateUser(user);
	}

	public List<User> findUserList(String sql) {
		return this.userDao.findUserList(sql);
	}

	public List<User> findActiveUserList(long num){
		return this.userDao.findActiveUserList(num);
	}

	@Override
	public UserExpand updateUserAndExpand(User user, UserExpand expand) throws DataException {
		this.updateUser(user);
		return this.userExpandDao.updateUserExpand(expand);
	}
}
